﻿namespace System.IO
{
    /// <summary>
    /// Stream Extension
    /// </summary>
    public static class StreamExtension
    {
        /// <summary>
        /// Stream to byte[]
        /// </summary>
        /// <param name="target"></param>
        /// <returns></returns>
        public static byte[] ToBytes(this Stream target)
        {
            if (target == null) return new byte[0]; //判断是否为空
            var stream = target as MemoryStream; //判断是否是MemoryStream
            if (stream != null) return stream.ToArray();
            using (var ms = new MemoryStream())
            {
                target.CopyTo(ms);
                return ms.ToArray();
            }
        }

        /// <summary>
        /// MemoryStream to byte[]
        /// </summary>
        /// <param name="target"></param>
        /// <returns></returns>
        public static byte[] ToBytes(this MemoryStream target)
        {
            if (target == null) return new byte[0]; //判断是否为空
            return target.ToArray();
        }
    }
}
